#include "table_selector_widget.h"
#include <QPainter>
#include <QDebug>

TableSelectorWidget::TableSelectorWidget(QWidget *parent) :
    QWidget(parent),
    m_rows(10),
    m_cols(10),
    m_hoverRows(0),
    m_hoverCols(0),
    m_boxWidth(20),
    m_boxHeight(20),
    m_boxGap(2)
{
    setMouseTracking(true);
}

void TableSelectorWidget::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);

    QPainter painter(this);
    int rows = width() / (m_boxWidth + m_boxGap);
    int cols = height() / (m_boxHeight + m_boxGap);
    int width = m_boxWidth;
    int height = m_boxHeight;
    int gap = m_boxGap;

    for (int i = 0; i < rows; i++)
    {
        for (int j = 0; j < cols; j++)
        {
            painter.drawRect(j * (width + gap), i * (height + gap), width, height);
        }
    }

    painter.setBrush(QBrush(QColor(0, 125, 0)));

    for (int i = 0; i < m_hoverRows && i < rows; i++)
    {
        for (int j = 0; j < m_hoverCols && j < cols; j++)
        {
            painter.drawRect(j * (width + gap), i * (height + gap), width, height);
        }
    }
}

void TableSelectorWidget::mouseMoveEvent(QMouseEvent *event)
{
    QPoint pt = event->pos();
    m_hoverRows = pt.y() / (m_boxHeight + m_boxGap) + 1;
    m_hoverCols = pt.x() / (m_boxWidth + m_boxGap) + 1;
    update();
    emit(hoverPosition(m_hoverRows, m_hoverCols));
}

void TableSelectorWidget::mousePressEvent(QMouseEvent *event)
{
    QPoint pt = event->pos();
    m_hoverRows = pt.y() / (m_boxHeight + m_boxGap) + 1;
    m_hoverCols = pt.x() / (m_boxWidth + m_boxGap) + 1;
    emit(selectPosition(m_hoverRows, m_hoverCols));
}

void TableSelectorWidget::leaveEvent(QEvent *event)
{
    Q_UNUSED(event);
    m_hoverRows = 0;
    m_hoverCols = 0;
    update();
    emit(hoverPosition(m_hoverRows, m_hoverCols));
}
